package base;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

public class Client {
	private String IPAddress;
	private int port;
	private Socket socket = null;

	public Client(String IPAddress,int port) {
		// TODO Auto-generated constructor stub
		this.IPAddress = IPAddress;
		this.port = port;
	}
	
	public void init(){
		try{
			socket = new Socket(this.IPAddress,this.port);
		}catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public Map<String,String> analyzeFromServer() throws IOException,JSONException{
		Map<String,String> message = new HashMap<String,String>();
		DataInputStream inputStream = null;
		Iterator keys  = null;
		inputStream = new DataInputStream(this.socket.getInputStream());
		JSONObject json = new JSONObject(inputStream);
		keys = json.keys();
        while(keys.hasNext()){
        	String key = keys.next().toString();
        	String value = json.getString(key);
        	message.put(key, value);
        }
		return message;
	}
	
	public void sendToServer(Map<String,String> message) throws IOException{
		DataOutputStream outputStream;
		JSONObject json = null;
		json = new JSONObject(message);  
        String jsonString = json.toString();                        
        //outputStream = new DataOutputStream(new BufferedOutputStream (socket.getOutputStream()));
        outputStream = new DataOutputStream(this.socket.getOutputStream());
        //System.out.println(jsonString);
        outputStream.writeUTF(jsonString);
	}
}
